package task;



import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class FileScanner {
    private ScanCallback callback;

    private ExecutorService pool = Executors.newFixedThreadPool(10);
    private volatile AtomicInteger count = new AtomicInteger();
    private Object lock = new Object();

    public FileScanner(ScanCallback callback) {
        this.callback = callback;
    }
    public FileScanner(){}

    /**
     * 扫描目录文件，开始不知道多少子文件夹
     * @param path
     */
    public void scan(String path){
        count.incrementAndGet();//根据目录扫描任务，计数器++i
        doScan(new File(path));
    }
    public void doScan(File dir){
        callback.callback(dir);
        pool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    File[] children = dir.listFiles();
                    if(children != null){
                        for(File file: children){//如果是文件夹，递归
                            if(file.isDirectory()){
                                count.incrementAndGet();//i++
                                doScan(file);
                            }
                        }
                    }
                } finally {
                    int c = count.decrementAndGet();
                    if(c == 0){
                        synchronized(lock){
                            lock.notify();
                            System.out.println("*********************************");
                        }
                    }
                }
            }
        });
    }

    public void waitFinish() throws InterruptedException {
        synchronized (lock){
            try {
                lock.wait();
            } finally {
                System.out.println("关闭线程池");
                pool.shutdown();
            }
        }
    }
}
